package com.lz.webflux.project.api.controller;

import com.lz.webflux.common.domain.ResponseVo;
import com.lz.webflux.common.utils.DateUtils;
import com.lz.webflux.project.api.service.ApiService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;


/**
 * 虚拟现场 webflux测试
 *
 * @author xpp
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    @Resource
    ApiService apiService;

    @GetMapping("/thread")
    public ResponseVo checkThread() throws InterruptedException {
        Thread.sleep(3000);
        System.out.println("虚拟线程：" + Thread.currentThread().isVirtual());
        System.out.println("线程ID：" + Thread.currentThread().threadId());
        return ResponseVo.success();
    }

    @GetMapping("/threadFlux")
    public Flux<ResponseVo> checkThreadFlux() throws InterruptedException {
        System.out.println("虚拟线程：" + Thread.currentThread().isVirtual());
        System.out.println("线程ID：" + Thread.currentThread().threadId());
        Flux<ResponseVo> t = Flux.create(sink -> new Thread(() -> {
            try {
                sink.next(apiService.deal()) ;
            } catch (InterruptedException e) {
            }
            sink.complete();

        }).start());
        return t;
    }

    @GetMapping("/threadMono")
    public Mono<ResponseVo> checkThreadMono() {

        System.out.println("虚拟线程：" + Thread.currentThread().isVirtual());
        System.out.println("线程ID：" + Thread.currentThread().threadId());
        return Mono.create(monoSink -> new Thread(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("Mono线程ID：" + Thread.currentThread().threadId());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //关键就在这里，只要在请求时的这个MonoSink里，无论是哪个线程里设置这个值就可以了
            monoSink.success(ResponseVo.success(DateUtils.getCurrentDateTimeWithMilliS()));
        }).start());
    }


}
